<template>
  <div class="file-preview">
    <!-- 预览对话框 -->
    <el-dialog
      :model-value="visible"
      @update:model-value="$emit('update:visible', $event)"
      :title="previewTitle"
      width="90%"
      top="2vh"
      :before-close="handleClose"
      :show-close="false"
      class="preview-dialog"
      :fullscreen="isFullscreen"
    >
      <!-- 工具栏 -->
      <template #header>
        <div class="preview-header">
          <div class="preview-title">
            <el-icon><Document /></el-icon>
            <span>{{ fileName }}</span>
            <el-tag :type="getFileTypeTagType()" size="small">{{ getFileTypeLabel() }}</el-tag>
          </div>
          <div class="preview-actions">
            <el-button
              text
              :icon="isFullscreen ? Minus : FullScreen"
              @click="toggleFullscreen"
              title="全屏切换"
            />
            <el-button
              text
              :icon="Close"
              @click="handleClose"
              title="关闭预览"
            />
          </div>
        </div>
      </template>

      <!-- 预览内容区域 -->
      <div class="preview-content" v-loading="loading">
        <!-- 视频预览 -->
        <div v-if="previewType === 'video'" class="video-preview">
          <VideoPlayer
            :video-url="previewUrl"
            :poster-url="posterUrl"
            @play="handleVideoPlay"
            @pause="handleVideoPause"
            @error="handleVideoError"
            @timeupdate="handleVideoTimeUpdate"
          />

          <div class="video-info">
            <p>文件大小: {{ formatFileSize(fileSize) }}</p>
            <p v-if="videoDuration">时长: {{ formatDuration(videoDuration) }}</p>
          </div>
        </div>

        <!-- 图片预览 -->
        <div v-else-if="previewType === 'image'" class="image-preview">
          <!-- 图片工具栏 -->
          <div class="image-toolbar">
            <div class="toolbar-left">
              <el-button-group>
                <el-button size="small" @click="zoomOut" :disabled="imageScale <= 0.1">
                  <el-icon><ZoomOut /></el-icon>
                </el-button>
                <el-button size="small" @click="resetZoom">
                  {{ Math.round(imageScale * 100) }}%
                </el-button>
                <el-button size="small" @click="zoomIn" :disabled="imageScale >= 5">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
              </el-button-group>

              <el-button-group style="margin-left: 8px;">
                <el-button size="small" @click="rotateLeft">
                  <el-icon><RefreshLeft /></el-icon>
                </el-button>
                <el-button size="small" @click="rotateRight">
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-button-group>

              <el-button-group style="margin-left: 8px;">
                <el-button size="small" @click="fitToWindow">适应窗口</el-button>
                <el-button size="small" @click="actualSize">原始尺寸</el-button>
              </el-button-group>

              <el-button
                size="small"
                style="margin-left: 8px;"
                :type="showImageDetails ? 'primary' : 'default'"
                @click="showImageDetails = !showImageDetails"
              >
                信息
              </el-button>
            </div>

            <div class="toolbar-right">
              <span class="image-info-text">
                {{ imageInfo.width }}×{{ imageInfo.height }} | {{ formatFileSize(fileSize) }}
              </span>
            </div>
          </div>

          <!-- 图片容器 -->
          <div
            class="image-container"
            ref="imageContainerRef"
            @mousedown="handleMouseDown"
            @mousemove="handleMouseMove"
            @mouseup="handleMouseUp"
            @mouseleave="handleMouseUp"
            @wheel="handleWheel"
            @contextmenu.prevent
          >
            <canvas
              ref="canvasRef"
              class="preview-canvas"
              :style="canvasStyle"
            />
          </div>

          <!-- 图片详细信息面板 -->
          <div class="image-details" v-if="showImageDetails">
            <div class="details-header">
              <h4>图片信息</h4>
              <el-button text @click="showImageDetails = false">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <div class="details-content">
              <div class="detail-item">
                <span class="label">文件名:</span>
                <span class="value">{{ fileName }}</span>
              </div>
              <div class="detail-item">
                <span class="label">尺寸:</span>
                <span class="value">{{ imageInfo.width }} × {{ imageInfo.height }} 像素</span>
              </div>
              <div class="detail-item">
                <span class="label">文件大小:</span>
                <span class="value">{{ formatFileSize(fileSize) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">格式:</span>
                <span class="value">{{ mimeType }}</span>
              </div>
            </div>
          </div>

          <!-- 快捷键提示 -->
          <div class="keyboard-hints" v-if="showKeyboardHints">
            <div class="hints-content">
              <h5>快捷键</h5>
              <div class="hint-item"><kbd>空格</kbd> 适应窗口</div>
              <div class="hint-item"><kbd>1</kbd> 原始尺寸</div>
              <div class="hint-item"><kbd>+/-</kbd> 缩放</div>
              <div class="hint-item"><kbd>R</kbd> 向右旋转</div>
              <div class="hint-item"><kbd>I</kbd> 显示信息</div>
            </div>
          </div>
        </div>

        <!-- PDF预览 -->
        <div v-else-if="previewType === 'pdf'" class="pdf-preview">
          <!-- PDF容器（iframe方案） -->
          <div
            class="pdf-container"
            ref="pdfContainerRef"
            style="width: 100%; height: 100%;"
          >
            <!-- iframe将在这里动态插入 -->
          </div>
        </div>

        <!-- 文档预览 -->
        <div v-else-if="previewType === 'document'" class="document-preview">
          <iframe
            :src="previewUrl"
            class="preview-document"
            @load="handleDocumentLoaded"
            @error="handleDocumentError"
          >
            您的浏览器不支持文档预览。
          </iframe>
          <div class="document-info">
            <p>文件大小: {{ formatFileSize(fileSize) }}</p>
            <p>注意: 文档预览功能正在完善中</p>
          </div>
        </div>

        <!-- 表格预览 -->
        <div v-else-if="previewType === 'spreadsheet'" class="spreadsheet-preview">
          <div class="spreadsheet-content">
            <el-table :data="spreadsheetData" border style="width: 100%">
              <el-table-column
                v-for="(column, index) in spreadsheetColumns"
                :key="index"
                :prop="column.prop"
                :label="column.label"
                min-width="120"
              />
            </el-table>
          </div>
          <div class="spreadsheet-info">
            <p>文件大小: {{ formatFileSize(fileSize) }}</p>
            <p>注意: 表格预览功能正在完善中</p>
          </div>
        </div>

        <!-- 不支持的文件类型 -->
        <div v-else class="unsupported-preview">
          <div class="unsupported-content">
            <el-icon size="64" color="#909399"><Warning /></el-icon>
            <h3>暂不支持此文件类型的预览</h3>
            <p>文件名: {{ fileName }}</p>
            <p>文件大小: {{ formatFileSize(fileSize) }}</p>
            <p>文件类型: {{ mimeType }}</p>

          </div>
        </div>

        <!-- 错误状态 -->
        <div v-if="error && previewType === 'unsupported'" class="error-preview">
          <div class="error-content">
            <el-icon size="64" color="#f56c6c"><CircleClose /></el-icon>
            <h3>预览失败</h3>
            <p>{{ error }}</p>
            <el-button @click="retryPreview">重试</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  FullScreen,
  Minus,
  Close
} from '@element-plus/icons-vue'
import { getImagePreview, getPdfPreview, getVideoPreview } from '@/api/modules/file'
// 动态导入VideoPlayer组件
import { defineAsyncComponent } from 'vue'
const VideoPlayer = defineAsyncComponent(() => import('./VideoPlayer.vue'))

// 组件属性
interface Props {
  visible: boolean
  fileId?: number
  fileName?: string
  mimeType?: string
  fileSize?: number
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  fileId: 0,
  fileName: '',
  mimeType: '',
  fileSize: 0
})

// 组件事件
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  close: []
  download: [fileId: number]
}>()

// 响应式数据
const loading = ref(false)
const error = ref('')
const isFullscreen = ref(false)
const previewUrl = ref('')
const posterUrl = ref('')
const videoDuration = ref(0)
const spreadsheetData = ref([])
const spreadsheetColumns = ref([])

// 视频控制相关
const currentTime = ref(0)
const isVideoPlaying = ref(false)
const isMuted = ref(false)
const volume = ref(100)
const playbackRate = ref(1)
const showVideoControls = ref(true)
const videoProgress = computed(() => {
  return videoDuration.value > 0 ? (currentTime.value / videoDuration.value) * 100 : 0
})

// 引用
const videoRef = ref<HTMLVideoElement>()

// 图片预览相关
const canvasRef = ref<HTMLCanvasElement>()
const imageContainerRef = ref<HTMLDivElement>()
const imageScale = ref(1)
const imageRotation = ref(0)
const imagePosition = ref({ x: 0, y: 0 })
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const showImageDetails = ref(false)
const showKeyboardHints = ref(false)
const imageInfo = ref({
  width: 0,
  height: 0,
  colorDepth: null as number | null
})
const imageElement = ref<HTMLImageElement | null>(null)

// PDF预览相关
const pdfCanvasRef = ref<HTMLCanvasElement>()
const pdfContainerRef = ref<HTMLDivElement>()
const pdfCurrentPage = ref(1)
const pdfTotalPages = ref(0)
const pdfScale = ref(1)
const pdfDocument = ref<any>(null)



// 计算属性
const previewTitle = computed(() => {
  return `文件预览 - ${props.fileName}`
})

const previewType = computed(() => {
  if (!props.mimeType) return 'unsupported'

  if (props.mimeType.startsWith('video/')) return 'video'
  if (props.mimeType.startsWith('image/')) return 'image'
  if (props.mimeType === 'application/pdf') return 'pdf'
  if (props.mimeType.includes('word')) return 'document'
  if (props.mimeType.includes('sheet') || props.mimeType.includes('excel')) return 'spreadsheet'

  return 'unsupported'
})

// Canvas样式计算
const canvasStyle = computed(() => {
  return {
    transform: `scale(${imageScale.value}) rotate(${imageRotation.value}deg) translate(${imagePosition.value.x}px, ${imagePosition.value.y}px)`,
    transformOrigin: 'center center',
    transition: isDragging.value ? 'none' : 'transform 0.3s ease',
    cursor: imageScale.value > 1 ? (isDragging.value ? 'grabbing' : 'grab') : 'default'
  }
})

// PDF Canvas样式计算
const pdfCanvasStyle = computed(() => {
  return {
    transform: `scale(${pdfScale.value})`,
    transformOrigin: 'center top',
    transition: 'transform 0.3s ease'
  }
})

// 监听visible变化
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.fileId) {
    loadPreview()
    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyDown)
  } else {
    resetPreview()
    // 移除键盘事件监听
    document.removeEventListener('keydown', handleKeyDown)
  }
})

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (!props.visible || previewType.value !== 'image') return

  switch (event.code) {
    case 'Space':
      event.preventDefault()
      fitToWindow()
      break
    case 'Digit1':
      event.preventDefault()
      actualSize()
      break
    case 'Equal':
    case 'NumpadAdd':
      event.preventDefault()
      zoomIn()
      break
    case 'Minus':
    case 'NumpadSubtract':
      event.preventDefault()
      zoomOut()
      break
    case 'KeyR':
      event.preventDefault()
      rotateRight()
      break
    case 'KeyI':
      event.preventDefault()
      showImageDetails.value = !showImageDetails.value
      break
    case 'KeyH':
      event.preventDefault()
      showKeyboardHints.value = !showKeyboardHints.value
      break
    case 'Escape':
      if (showImageDetails.value) {
        showImageDetails.value = false
      } else if (showKeyboardHints.value) {
        showKeyboardHints.value = false
      }
      break
  }
}

// 加载预览
const loadPreview = async () => {
  if (!props.fileId) return

  loading.value = true
  error.value = ''

  try {
    // 使用智能预览 URL 生成
    const { smartPreviewFile } = await import('@/api/modules/fileUrl')

    switch (previewType.value) {
      case 'video':
        // 视频预览使用blob方式，避免认证问题
        await loadVideoBlob()
        break
      case 'image':
        await loadImageBlob()
        break
      case 'pdf':
        await loadPdfWithIframe()
        break
      case 'document':
        previewUrl.value = await smartPreviewFile(props.fileId, props.mimeType || '')
        break
      case 'spreadsheet':
        await loadSpreadsheetData()
        break
      default:
        error.value = '不支持的文件类型'
    }

  } catch (err) {
    console.error('加载预览失败:', err)
    error.value = '加载预览失败'
  } finally {
    loading.value = false
  }
}

// 生成带认证的视频预览URL
const generateVideoPreviewUrl = () => {
  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    error.value = '未登录，无法预览视频'
    return ''
  }

  // 返回带token的URL
  return `http://localhost:8080/api/preview/video/${props.fileId}?token=${token}`
}

// 加载视频blob数据
const loadVideoBlob = async () => {
  try {
    const response = await getVideoPreview(props.fileId)
    const blob = new Blob([response.data], { type: props.mimeType || 'video/mp4' })
    previewUrl.value = window.URL.createObjectURL(blob)
  } catch (err) {
    console.error('加载视频失败:', err)
    error.value = '视频加载失败'
  }
}

// 加载图片blob数据并绘制到canvas
const loadImageBlob = async () => {
  try {
    // 使用导入的API函数
    const response = await getImagePreview(props.fileId)

    // 创建blob URL
    const blob = new Blob([response.data], { type: props.mimeType || 'image/jpeg' })
    const url = window.URL.createObjectURL(blob)

    // 创建图片元素
    const img = new Image()
    img.onload = () => {
      // 设置图片信息
      imageInfo.value.width = img.naturalWidth
      imageInfo.value.height = img.naturalHeight
      imageElement.value = img

      // 绘制到canvas
      drawImageToCanvas()

      // 初始化缩放以适应容器
      nextTick(() => {
        fitToWindow()
      })

      // 清理blob URL
      window.URL.revokeObjectURL(url)
    }

    img.onerror = () => {
      error.value = '图片加载失败'
      window.URL.revokeObjectURL(url)
    }

    img.src = url

  } catch (err) {
    console.error('加载图片失败:', err)
    error.value = '图片加载失败'
  }
}

// 将图片绘制到canvas
const drawImageToCanvas = () => {
  if (!canvasRef.value || !imageElement.value) return

  const canvas = canvasRef.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 设置canvas尺寸为图片原始尺寸
  canvas.width = imageElement.value.naturalWidth
  canvas.height = imageElement.value.naturalHeight

  // 清除canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 绘制图片
  ctx.drawImage(imageElement.value, 0, 0)
}



// 原来的PDF.js方案作为备用
const loadPdfBlob = async () => {
  try {
    console.log('开始加载PDF...')

    // 动态导入PDF.js
    const pdfjsLib = await import('pdfjs-dist')
    console.log('PDF.js导入成功')

    // 检查实际的PDF.js版本并使用匹配的worker
    console.log('PDF.js版本:', pdfjsLib.version)
    console.log('PDF.js构建:', pdfjsLib.build)

    // 使用本地worker或unpkg CDN
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.worker.min.js'
    console.log('已设置3.x版本worker:', pdfjsLib.GlobalWorkerOptions.workerSrc)

    // 使用API获取PDF数据
    console.log('开始获取PDF数据...')
    const response = await getPdfPreview(props.fileId)
    console.log('PDF响应状态:', response.status)
    console.log('PDF响应头:', response.headers)

    // 检查响应数据
    if (!response.data || response.data.size === 0) {
      throw new Error('PDF数据为空')
    }

    console.log('PDF数据大小:', response.data.size, 'bytes')
    console.log('PDF数据类型:', response.data.type)

    // 检查是否是有效的PDF数据
    const arrayBuffer = await response.data.arrayBuffer()
    const uint8Array = new Uint8Array(arrayBuffer)
    const pdfHeader = String.fromCharCode(...uint8Array.slice(0, 8))
    console.log('PDF文件头:', pdfHeader)
    console.log('PDF前20字节:', Array.from(uint8Array.slice(0, 20)).map(b => b.toString(16).padStart(2, '0')).join(' '))

    if (!pdfHeader.startsWith('%PDF')) {
      console.error('无效的PDF文件头:', pdfHeader)
      throw new Error('无效的PDF文件格式')
    }

    // 创建blob URL
    const blob = new Blob([arrayBuffer], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    console.log('Blob URL创建成功:', url)

    // 加载PDF文档 - 使用最简单的配置
    console.log('开始加载PDF文档...')
    const loadingTask = pdfjsLib.getDocument(url)

    // 添加加载事件监听
    loadingTask.onProgress = (progress: any) => {
      console.log('PDF加载进度:', progress)
    }

    loadingTask.onPassword = (callback: any, reason: any) => {
      console.log('PDF需要密码:', reason)
      // 暂时不处理密码保护的PDF
      callback('')
    }

    // 添加超时处理（10秒）
    const pdf = await Promise.race([
      loadingTask.promise.catch((err: any) => {
        console.error('PDF.js加载错误详情:', err)
        console.error('错误类型:', err.name)
        console.error('错误消息:', err.message)
        console.error('错误堆栈:', err.stack)
        throw err
      }),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('PDF加载超时')), 10000)
      )
    ]) as any
    console.log('PDF文档加载成功，页数:', pdf.numPages)

    // 安全地存储PDF文档
    pdfDocument.value = pdf
    pdfTotalPages.value = pdf.numPages
    pdfCurrentPage.value = 1

    // 等待DOM更新后再渲染
    await nextTick()

    // 渲染第一页
    console.log('开始渲染第一页...')
    await renderPdfPage(1)

    // 清理blob URL
    window.URL.revokeObjectURL(url)

  } catch (err) {
    console.error('加载PDF失败:', err)

    // 如果PDF.js失败，回退到iframe方案
    if (err.message.includes('private field') || err.message.includes('超时')) {
      console.log('PDF.js失败，回退到iframe预览方案...')
      try {
        // 使用iframe显示PDF
        await loadPdfWithIframe()
        return // 成功退出
      } catch (iframeErr) {
        console.error('iframe方案也失败:', iframeErr)
      }
    }

    error.value = `PDF加载失败: ${err.message}`
  }
}



// 使用iframe加载PDF方案
const loadPdfWithIframe = async () => {
  console.log('使用iframe方案加载PDF...')

  try {
    // 获取PDF数据
    const response = await getPdfPreview(props.fileId)
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)

    console.log('PDF blob URL创建成功:', url)

    // 等待DOM更新
    await nextTick()

    // 插入iframe到容器中
    if (pdfContainerRef.value) {
      // 创建iframe元素
      const iframe = document.createElement('iframe')
      iframe.src = url
      iframe.style.cssText = `
        width: 100%;
        height: 100%;
        border: none;
        background: white;
      `
      iframe.title = 'PDF预览'

      // 清空容器并插入iframe
      pdfContainerRef.value.innerHTML = ''
      pdfContainerRef.value.appendChild(iframe)
      console.log('iframe已插入到容器中')

    } else {
      throw new Error('PDF容器不存在')
    }

    console.log('iframe PDF加载完成，安全控制已启用')

    // 清理blob URL（延长时间，确保iframe加载完成）
    setTimeout(() => {
      window.URL.revokeObjectURL(url)
      console.log('blob URL已清理')
    }, 300000) // 5分钟后清理

  } catch (err) {
    console.error('iframe PDF加载失败:', err)
    error.value = `PDF加载失败: ${err.message}`
  }
}

// 渲染PDF页面到canvas
const renderPdfPage = async (pageNumber: number) => {
  if (!pdfDocument.value || !pdfCanvasRef.value) return

  try {
    console.log('开始渲染页面:', pageNumber)

    // 使用3.x版本的标准页面获取方式
    const page = await pdfDocument.value.getPage(pageNumber)
    console.log('页面获取成功')

    const canvas = pdfCanvasRef.value
    const ctx = canvas.getContext('2d')

    if (!ctx) {
      console.error('无法获取canvas context')
      return
    }

    // 计算合适的缩放比例
    const containerWidth = pdfContainerRef.value?.clientWidth || 800
    const viewport = page.getViewport({ scale: 1.0 })
    const scale = Math.min((containerWidth - 40) / viewport.width, 1.5) // 限制最大缩放

    const scaledViewport = page.getViewport({ scale: scale * pdfScale.value })
    console.log('视口计算完成:', scaledViewport.width, 'x', scaledViewport.height)

    // 设置canvas尺寸
    canvas.width = scaledViewport.width
    canvas.height = scaledViewport.height

    // 设置canvas样式尺寸（防止模糊）
    canvas.style.width = scaledViewport.width + 'px'
    canvas.style.height = scaledViewport.height + 'px'

    // 清除canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 渲染页面
    const renderContext = {
      canvasContext: ctx,
      viewport: scaledViewport,
      enableWebGL: false // 禁用WebGL避免兼容性问题
    }

    console.log('开始渲染到canvas...')
    const renderTask = page.render(renderContext)
    await renderTask.promise
    console.log('页面渲染完成')

  } catch (err) {
    console.error('渲染PDF页面失败:', err)
    console.error('错误详情:', err.message)
    console.error('错误堆栈:', err.stack)
    error.value = `PDF渲染失败: ${err.message}`
  }
}

// 图片缩放控制
const zoomIn = () => {
  imageScale.value = Math.min(imageScale.value * 1.2, 5)
}

const zoomOut = () => {
  imageScale.value = Math.max(imageScale.value / 1.2, 0.1)
}

const resetZoom = () => {
  imageScale.value = 1
  imagePosition.value = { x: 0, y: 0 }
}

const fitToWindow = () => {
  if (!canvasRef.value || !imageContainerRef.value) return

  const container = imageContainerRef.value
  const containerWidth = container.clientWidth - 40 // 留边距
  const containerHeight = container.clientHeight - 40

  const imageWidth = imageInfo.value.width
  const imageHeight = imageInfo.value.height

  const scaleX = containerWidth / imageWidth
  const scaleY = containerHeight / imageHeight

  imageScale.value = Math.min(scaleX, scaleY, 1) // 不超过原始尺寸
  imagePosition.value = { x: 0, y: 0 }
}

const actualSize = () => {
  imageScale.value = 1
  imagePosition.value = { x: 0, y: 0 }
}

// 图片旋转
const rotateLeft = () => {
  imageRotation.value -= 90
}

const rotateRight = () => {
  imageRotation.value += 90
}

// 鼠标拖拽
const handleMouseDown = (event: MouseEvent) => {
  if (imageScale.value <= 1) return

  isDragging.value = true
  dragStart.value = {
    x: event.clientX - imagePosition.value.x,
    y: event.clientY - imagePosition.value.y
  }
  event.preventDefault()
}

const handleMouseMove = (event: MouseEvent) => {
  if (!isDragging.value) return

  imagePosition.value = {
    x: event.clientX - dragStart.value.x,
    y: event.clientY - dragStart.value.y
  }
}

const handleMouseUp = () => {
  isDragging.value = false
}

// 鼠标滚轮缩放
const handleWheel = (event: WheelEvent) => {
  event.preventDefault()

  if (event.deltaY < 0) {
    zoomIn()
  } else {
    zoomOut()
  }
}

// PDF控制方法（iframe方案不需要这些控制）
const pdfPrevPage = async () => {
  // iframe方案由浏览器自己处理分页
  console.log('iframe方案不支持程序化分页控制')
}

const pdfNextPage = async () => {
  // iframe方案由浏览器自己处理分页
  console.log('iframe方案不支持程序化分页控制')
}

const pdfZoomIn = async () => {
  // iframe方案由浏览器自己处理缩放
  console.log('iframe方案不支持程序化缩放控制')
}

const pdfZoomOut = async () => {
  // iframe方案由浏览器自己处理缩放
  console.log('iframe方案不支持程序化缩放控制')
}

const pdfResetZoom = async () => {
  // iframe方案由浏览器自己处理缩放
  console.log('iframe方案不支持程序化缩放控制')
}

const pdfFitToWidth = async () => {
  // iframe方案由浏览器自己处理缩放
  console.log('iframe方案不支持程序化缩放控制')
}

// PDF鼠标滚轮事件
const handlePdfWheel = (event: WheelEvent) => {
  event.preventDefault()

  if (event.ctrlKey) {
    // Ctrl + 滚轮缩放
    if (event.deltaY < 0) {
      pdfZoomIn()
    } else {
      pdfZoomOut()
    }
  } else {
    // 普通滚轮翻页
    if (event.deltaY < 0) {
      pdfPrevPage()
    } else {
      pdfNextPage()
    }
  }
}

// 图片事件处理（保留兼容性）
const handleImageLoaded = () => {
  // 图片加载完成
}

const handleImageError = () => {
  // 图片加载失败，但不显示全局错误，因为图片可能通过blob方式正常加载
  console.warn('图片URL加载失败，可能使用blob方式加载')
}

// 加载表格数据
const loadSpreadsheetData = async () => {
  try {
    const response = await fetch(`http://localhost:8080/api/preview/spreadsheet/${props.fileId}`)
    const data = await response.json()

    if (data.sheets && data.sheets.length > 0) {
      const sheet = data.sheets[0]
      spreadsheetData.value = sheet.data.slice(1).map((row: any[], index: number) => {
        const obj: any = { id: index }
        sheet.data[0].forEach((header: string, colIndex: number) => {
          obj[`col${colIndex}`] = row[colIndex] || ''
        })
        return obj
      })

      spreadsheetColumns.value = sheet.data[0].map((header: string, index: number) => ({
        prop: `col${index}`,
        label: header || `列${index + 1}`
      }))
    }
  } catch (err) {
    console.error('加载表格数据失败:', err)
    error.value = '加载表格数据失败'
  }
}

// 重置预览
const resetPreview = () => {
  previewUrl.value = ''
  error.value = ''
  loading.value = false
  videoDuration.value = 0
  spreadsheetData.value = []
  spreadsheetColumns.value = []
}

// 事件处理
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}



const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

const retryPreview = () => {
  loadPreview()
}

// 视频事件处理
const handleVideoLoadStart = () => {
  // 视频开始加载
}

const handleVideoLoaded = () => {
  // 视频加载完成，更新时长信息
  if (videoRef.value) {
    videoDuration.value = videoRef.value.duration
  }
}

const handleVideoError = (event: Event) => {
  console.error('视频加载错误:', event)
  error.value = '视频加载失败'
}

const handleVideoTimeUpdate = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime
  }
}

const handleVideoPlay = () => {
  isVideoPlaying.value = true
}

const handleVideoPause = () => {
  isVideoPlaying.value = false
}

const handleVideoEnded = () => {
  isVideoPlaying.value = false
  currentTime.value = 0
}

// 视频控制方法
const toggleVideoPlay = () => {
  if (videoRef.value) {
    if (isVideoPlaying.value) {
      videoRef.value.pause()
    } else {
      videoRef.value.play()
    }
  }
}

const toggleMute = () => {
  if (videoRef.value) {
    videoRef.value.muted = !videoRef.value.muted
    isMuted.value = videoRef.value.muted
  }
}

const handleVolumeChange = (value: number) => {
  if (videoRef.value) {
    videoRef.value.volume = value / 100
  }
}

const handlePlaybackRateChange = (rate: number) => {
  if (videoRef.value) {
    videoRef.value.playbackRate = rate
  }
}

const toggleVideoFullscreen = () => {
  if (videoRef.value) {
    if (document.fullscreenElement) {
      document.exitFullscreen()
    } else {
      videoRef.value.requestFullscreen()
    }
  }
}

const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}



// PDF事件处理
const handlePdfLoaded = () => {
  // PDF加载完成
}

const handlePdfError = () => {
  error.value = 'PDF加载失败'
}

// 文档事件处理
const handleDocumentLoaded = () => {
  // 文档加载完成
}

const handleDocumentError = () => {
  error.value = '文档加载失败'
}

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${minutes}:${secs.toString().padStart(2, '0')}`
  }
}

const getFileTypeLabel = (): string => {
  switch (previewType.value) {
    case 'video': return '视频'
    case 'image': return '图片'
    case 'pdf': return 'PDF'
    case 'document': return '文档'
    case 'spreadsheet': return '表格'
    default: return '未知'
  }
}

const getFileTypeTagType = (): string => {
  switch (previewType.value) {
    case 'video': return 'success'
    case 'image': return 'primary'
    case 'pdf': return 'warning'
    case 'document': return 'info'
    case 'spreadsheet': return 'success'
    default: return 'info'
  }
}
</script>

<style lang="scss" scoped>
.file-preview {
  .preview-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
    }
  }
  
  .preview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    
    .preview-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
    }
    
    .preview-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .preview-content {
    height: 85vh;
    display: flex;
    flex-direction: column;
  }
  
  // 视频预览样式
  .video-preview {
    display: flex;
    flex-direction: column;
    align-items: center;

    .video-container {
      position: relative;
      width: 100%;
      max-width: 100%;

      .preview-video {
        width: 100%;
        max-width: 100%;
        height: auto;
        max-height: 70vh;
        background: #000;
      }

      .video-controls-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
        padding: 20px;
        color: white;

        .video-progress {
          margin-bottom: 12px;

          .progress-bar {
            width: 100%;
            height: 4px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 2px;
            overflow: hidden;
            margin-bottom: 8px;

            .progress-filled {
              height: 100%;
              background: var(--el-color-primary);
              transition: width 0.1s ease;
            }
          }

          .time-display {
            font-size: 12px;
            text-align: center;
          }
        }

        .video-control-buttons {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 12px;

          .volume-control {
            display: flex;
            align-items: center;
          }
        }
      }

      &:hover .video-controls-overlay {
        opacity: 1;
      }
    }

    .video-info {
      margin-top: 16px;
      text-align: center;
      color: var(--el-text-color-secondary);

      p {
        margin: 4px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }
    }
  }
  
  // 图片预览样式
  .image-preview {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;

    .image-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      background: var(--el-bg-color-page);
      border-bottom: 1px solid var(--el-border-color-light);

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .toolbar-right {
        .image-info-text {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }

    .image-container {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      background: var(--el-bg-color);
      position: relative;
      min-height: 0; // 重要：允许flex子项收缩

      .preview-canvas {
        max-width: none;
        max-height: none;
        user-select: none;
        pointer-events: none;
      }
    }

    .image-details {
      position: absolute;
      top: 60px;
      right: 16px;
      width: 280px;
      background: var(--el-bg-color-overlay);
      backdrop-filter: blur(10px);
      border-radius: 8px;
      box-shadow: 0 4px 12px var(--el-box-shadow-dark);
      border: 1px solid var(--el-border-color-light);
      z-index: 100;

      .details-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid var(--el-border-color-lighter);

        h4 {
          margin: 0;
          font-size: 14px;
          font-weight: 600;
        }
      }

      .details-content {
        padding: 12px 16px;

        .detail-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;
          font-size: 12px;

          .label {
            color: var(--el-text-color-secondary);
            font-weight: 500;
          }

          .value {
            color: var(--el-text-color-primary);
            text-align: right;
            max-width: 150px;
            word-break: break-all;
          }
        }
      }
    }

    .keyboard-hints {
      position: absolute;
      bottom: 16px;
      left: 16px;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 12px 16px;
      border-radius: 8px;
      font-size: 12px;
      z-index: 100;

      .hints-content {
        h5 {
          margin: 0 0 8px 0;
          font-size: 13px;
          font-weight: 600;
        }

        .hint-item {
          margin-bottom: 4px;

          kbd {
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
            margin-right: 8px;
          }
        }
      }
    }
  }
  
  // PDF预览样式
  .pdf-preview {
    display: flex;
    flex-direction: column;
    height: 100%;

    .pdf-container {
      flex: 1;
      background: var(--el-bg-color);
      min-height: 0;
    }
  }
  
  // 文档预览样式
  .document-preview {
    .preview-document {
      width: 100%;
      height: 70vh;
      border: none;
    }
    
    .document-info {
      padding: 16px;
      text-align: center;
      color: var(--el-text-color-secondary);
    }
  }
  
  // 表格预览样式
  .spreadsheet-preview {
    .spreadsheet-content {
      max-height: 60vh;
      overflow: auto;
    }
    
    .spreadsheet-info {
      padding: 16px;
      text-align: center;
      color: var(--el-text-color-secondary);
    }
  }
  
  // 不支持的文件类型样式
  .unsupported-preview,
  .error-preview {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 400px;
    
    .unsupported-content,
    .error-content {
      text-align: center;
      
      h3 {
        margin: 16px 0;
        color: var(--el-text-color-primary);
      }
      
      p {
        margin: 8px 0;
        color: var(--el-text-color-secondary);
      }
      
      .el-button {
        margin-top: 16px;
        margin-left: 8px;
      }
    }
  }
}

// 全屏模式样式修复 - 支持夜间模式
:deep(.el-dialog.is-fullscreen) {
  .el-dialog__header {
    position: relative;
    z-index: 1000;
    background: var(--el-bg-color-overlay);
    backdrop-filter: blur(10px);
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .preview-actions {
    .el-button {
      background: var(--el-bg-color);
      border: 1px solid var(--el-border-color-light);
      color: var(--el-text-color-primary);

      &:hover {
        background: var(--el-bg-color-page);
        border-color: var(--el-color-primary);
        color: var(--el-color-primary);
      }
    }
  }

  // 确保全屏模式下的内容区域也适配夜间模式
  .preview-content {
    background: var(--el-bg-color);
    color: var(--el-text-color-primary);
  }

  // PDF容器在全屏模式下的夜间适配
  .pdf-container {
    background: var(--el-bg-color);

    iframe {
      background: var(--el-bg-color);
    }
  }

  // 图片预览在全屏模式下的夜间适配
  .image-container {
    background: var(--el-bg-color);
  }

  // 图片工具栏在全屏模式下的夜间适配
  .image-toolbar {
    background: var(--el-bg-color-page);
    border-bottom: 1px solid var(--el-border-color-light);
  }

  // 图片详情面板在全屏模式下的夜间适配
  .image-details {
    background: var(--el-bg-color-overlay);
    color: var(--el-text-color-primary);
    box-shadow: 0 4px 12px var(--el-box-shadow-dark);

    .details-header {
      border-bottom: 1px solid var(--el-border-color-lighter);

      h4 {
        color: var(--el-text-color-primary);
      }
    }

    .details-content {
      .detail-item {
        .label {
          color: var(--el-text-color-secondary);
        }

        .value {
          color: var(--el-text-color-primary);
        }
      }
    }
  }
}
</style>
